package bar.dark.lee.alarm.common;

import com.cauly.android.ad.AdInfo;
import com.cauly.android.ad.AdListener;
import com.cauly.android.ad.AdView;

import net.daum.mobilead.AdConfig;
import net.daum.mobilead.AdHttpListener;
import net.daum.mobilead.MobileAdView;
import android.content.Context;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import bar.dark.lee.alarm.BDContents;

public class BDAdView implements AdHttpListener, AdListener {
	
	private int max = 1;
	private int min = 0;
	
	private int adamMin = 0;
	private int adamMax = 5;
	
	private int caulyMin = 0;
	private int caulyMax = 5;
	
	private Context context;
	private LinearLayout adviewLinear;
	
	private final static int ADAM = 1;
	private final static int ADAM_TAD = 12;
	private final static int ADAM_ADCUBE = 13;
	private final static int ADAM_CAULY = 14;
	
	private final static int TAD = 2;
	private final static int TAD_ADCUBE = 23;
	
	private final static int ADCUBE = 3;
	
	private static final int CAULY = 4;
	
	private final static int ALL = 100;
	
	private final static int KIND = ADAM_CAULY;
	
	private boolean isReceive = false;
	
	private MobileAdView adamView = null;
	
	private AdView caulyView = null;
	private AdInfo adinfo;
	
	LinearLayout.LayoutParams params;
	
	public BDAdView(Context context, LinearLayout adviewLinear) {
		this.context = context;
		this.adviewLinear = adviewLinear;
		this.adviewLinear.setVisibility(View.GONE);
		
		Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		int displayHeight = display.getHeight();
		
		double height = (double)(displayHeight / 10);
		
		params = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, (int)height);
		
		//광고 정보 셋팅
        adinfo = new AdInfo();
        adinfo.setPriority(Thread.NORM_PRIORITY); //Thread 우선 순위 (1 ~ 10) 
        adinfo.initData(BDContents.CAULY_APP_KEY, "cpm", "all", "all", "off", "default", "yes", 0, false);
	}
	
	public void startBDAd() {
		
		isReceive = false;
		
		switch (KIND) {
			case ADAM:
//				BDAdViewDestroy();
				adamCpcAd();
				break;
			case ADAM_TAD:
//				BDAdViewDestroy();
				adamCpcAd();
				break;
			case ADAM_ADCUBE:
//				BDAdViewDestroy();
				adamCpcAd();
				break;
			case ADAM_CAULY:
//				BDAdViewDestroy();
				adamCpcAd();
				break;
			case CAULY:
//				BDAdViewDestroy();
				caulyCpcAd();
				break;
			case TAD:
//				BDAdViewDestroy();
//				tadCpcAd();
				break;	
			case TAD_ADCUBE:
//				BDAdViewDestroy();
//				tadCpcAd();
				break;	
			case ADCUBE:
//				BDAdViewDestroy();
//				adcubeCpcAd();
				break;	
			case ALL:
//				BDAdViewDestroy();
				adamCpcAd();
			default:
				break;
		}
	}
	
//	public void startAdam() {
//		BDAdViewDestroy();
//		adamCpcAd();
//	}
	
//	public void startTad() {
//		BDAdViewDestroy();
//		tadCpcAd();
//	}
//	
//	public void startAdcube() {
//		BDAdViewDestroy();
//		adcubeCpcAd();
//	}
	
	public void BDAdViewDestroy() {
		destroyAdamView();
		destroyCaulyView();
//		destroyTadView();
//		destroyAdcubeView();
	}
	
	public void BDAdViewPause() {
		pauseAdamView();
		pauseCaulyView();
//		pauseTadView();
//		pauseAdcubeView();
	}
	
	public void BDAdViewResume() {
		
//		if (adamMin > adamMax)
//		{
//			min = 0;
//			adamMin = 0;
//			adamCpcAd();
//		}
		
//		if (!isReceive)
//		{
//			adamCpcAd();
//		}
		
		min = 0;
		adamMin = 0;
		caulyMin = 0;
		
		if (adamView != null)
		{
			if (!adamView.hasAd())
			{
				startBDAd();
			}
		}
		else
		{
			startBDAd();
		}
		
//		resumeAdamView();
//		resumeCaulyView();
//		resumeTadView();
//		resumeAdcubeView();
	}
	
	// ad@m //

	//CPC광고
	private void adamCpcAd() {
		
//		if (adamMin >= adamMax)
//		{
//			return;
//		}
//		adamMin++;
		
		if (adamView != null)
		{
			if (adamView.hasAd())
			{
				return;
			}
		}
		
//		adviewLinear.setVisibility(View.INVISIBLE);
		
		// 할당 받은 clientId 설정
		AdConfig.setClientId(BDContents.ADAM_APP_KEY);
		
		// Ad@m 광고 뷰 생성 및 설정
		adamView = new MobileAdView(context);
        adamView.setGravity(Gravity.BOTTOM);
        adamView.setRequestInterval(20);
 		adamView.setAdListener(this);
 		adamView.setVisibility(View.VISIBLE);
	}
	
	@Override
	public void failedDownloadAd_AdListener(int errorno, String errMsg) 
	{
		// fail to receive Ad
		
		if (adamView != null)
		{
			adamView.destroy();
			adamView = null;
		}
		
		if (adamMin <= adamMax)
		{
			adamCpcAd();
			adamMin++;
			return;
		}
		
		isReceive = false;
		
		switch (KIND) {
			case ADAM:
//				BDAdViewDestroy();
				adamCpcAd();
				break;
			case ADAM_TAD:
//				BDAdViewDestroy();
//				tadCpcAd();
				break;
			case ADAM_ADCUBE:
//				BDAdViewDestroy();
				adamCpcAd();
				break;
			case ADAM_CAULY:
//				BDAdViewDestroy();
				caulyCpcAd();
				break;
			case ALL:
//				BDAdViewDestroy();
//				tadCpcAd();
			default:
				break;
		}
	}

	@Override
	public void didDownloadAd_AdListener() {
		// success to receive Ad
//		min = 0;
		
//		if ( ! isReceive )
//		{
			if (adamView != null)
			{
				
				for (int i = 0; i < adviewLinear.getChildCount(); i++)
				{
					View child = adviewLinear.getChildAt(i);
					
					if (child instanceof MobileAdView)
					{
						adviewLinear.removeView(child);
					}
					else if (child instanceof AdView)
					{
						adviewLinear.removeView(child);
					}
				}
				
				adviewLinear.setVisibility(View.VISIBLE);
				adviewLinear.addView(adamView, params);
				isReceive = true;
				
			}
//		}
	}
	
	private void resumeAdamView()
	{
		if (adamView != null) {
			adamView.resume();
		}
	}
	
	private void resumeCaulyView()
	{
		if (caulyView != null)
		{
			caulyView.setVisibility(View.VISIBLE);
		}
	}
	
	private void pauseAdamView() {
		if (adamView != null) {
			adamView.pause();
		}
	}
	
	private void pauseCaulyView()
	{
		if (caulyView != null)
		{
			caulyView.setVisibility(View.INVISIBLE);
		}
	}
	
	private void destroyAdamView() {
		if (adviewLinear.getChildCount() > 0)
		{
			for (int i = 0; i < adviewLinear.getChildCount(); i++)
			{
				View child = adviewLinear.getChildAt(i);
				
				if (child instanceof MobileAdView)
				{
					MobileAdView adV = (MobileAdView) child;
					adviewLinear.removeView(adV);
					adV.setVisibility(View.GONE);
					adV.destroy();
					adV = null;
				}
			}
		}
	}
	
	private void destroyCaulyView()
	{
		if (adviewLinear.getChildCount() > 0)
		{
			for (int i = 0; i < adviewLinear.getChildCount(); i++)
			{
				View child = adviewLinear.getChildAt(i);
				
				if (child instanceof AdView)
				{
					AdView adV = (AdView) child;
					adviewLinear.removeView(adV);
					adV.setVisibility(View.GONE);
					adV = null;
				}
			}
		}
		
		if (adinfo != null) 
		{
			adinfo = null;
		}
	}
	
	// cauly //
	
		//유료 광고일때
	    final int CAULY_CHARGEABLE_AD = 0;
	    //무료 광고일때
	    final int CAULY_NON_CHARGEABLE_AD = 100;
	    //전면광고 없음
	    final int CAULY_INTERSTITIAL_NO_FILLED_AD = 200;
	    //앱코드 불일치
	    final int CAULY_INVALID_APPCODE = 400;
	    //카울리 서버 에러
	    final int CAULY_SERVER_CONNECTION_ERROR = 500;
	    //전면광고 최소 요청 주기 미만.
	    final int CAULY_INTERSTITIAL_NOT_PERMITED = -200;
	    //SDK 에러.
	    final int CAULY_SDK_ERROR = -100;
	    
	    @Override
		public void onCloseInterstitialAd() {
			// TODO Auto-generated method stub
			caulyCpcAd();
		}
	    
	  //CPC광고
		private void caulyCpcAd()
		{
			if (caulyMin >= caulyMax)
			{
				return;
			}
			
			caulyMin++;
			
			adinfo = new AdInfo();
	        adinfo.setPriority(Thread.NORM_PRIORITY); //Thread 우선 순위 (1 ~ 10) 
	        adinfo.initData(BDContents.CAULY_APP_KEY, 
	        		"cpc", "all", "all", "off", "left_slide", "yes", 30, true);
	        
	        //광고 View
	        caulyView = new AdView(context); 
			caulyView.setVisibility(View.VISIBLE);
			caulyView.setAdListener(this);
		}
	    
		@Override
		public void onFailedToReceiveAd(boolean arg0) {
			
			if( caulyView != null ) 
			{
				caulyView.setVisibility(View.GONE);
				caulyView = null;
			}
			
			isReceive = false;
			
			switch (KIND) 
			{
				case ADAM_CAULY:
					caulyCpcAd();
					break;
				case CAULY:
					caulyCpcAd();
					break;
				case ALL:
					adamCpcAd();
					break;
				default:
					break;
			}
			return;
			//}
		}
		
		@Override
		public void onReceiveAd() {
			if(caulyView.getErrorCode() == CAULY_INVALID_APPCODE) {
				// 앱코드가 부정확하므로 확인이 필요합니다. 
			}
			
			if(!caulyView.isChargeableAd())
			{
				// TODO 타사 광고를 호출하거나 개발사 내부 광고를 호출
				switch (KIND) 
				{
					case ADAM_CAULY:
						caulyCpcAd();
						break;
					case CAULY:
						caulyCpcAd();
						break;
					case ALL:
						adamCpcAd();
						break;
					default:
						break;
				}
				return;
			} 
			
			if(caulyView.getErrorCode() == CAULY_NON_CHARGEABLE_AD) 
			{
				// TODO 타사 광고를 호출하거나 개발사 내부 광고를 호출
				switch (KIND) 
				{
					case ADAM_CAULY:
						caulyCpcAd();
						break;
					case CAULY:
						caulyCpcAd();
						break;
					case ALL:
						adamCpcAd();
						break;
					default:
						break;
				}
				return;
			}
			
			
//			if ( ! isReceive )
//			{
				if (caulyView != null)
				{
					for (int i = 0; i < adviewLinear.getChildCount(); i++)
					{
						View child = adviewLinear.getChildAt(i);
						
						if (child instanceof AdView)
						{
							adviewLinear.removeView(child);
						}
						else if (child instanceof MobileAdView)
						{
							adviewLinear.removeView(child);
						}
					}
					
//					LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//							LayoutParams.FILL_PARENT,
//							LayoutParams.WRAP_CONTENT);
					
					adviewLinear.setVisibility(View.VISIBLE);
					adviewLinear.addView(caulyView, params);
					isReceive = true;
				}
//			}
		}
		
		//전면광고
		private void caulyInterstitialAd(){
	        //광고 View
	        caulyView = new AdView(context); 
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT);	
			caulyView.setVisibility(View.VISIBLE);
			caulyView.setAdListener(this);
			
			adviewLinear.addView(caulyView, params);
		}
	
//	// adcube //
//	
//	public void adcubeCpcAd() {
//		
//		try 
//		{
////			adviewLinear.setVisibility(View.INVISIBLE);
//			
//			// 광고 붙이기
//			final String appid = BDConstents.ADCUBE_APP_KEY;
//	
//			adcubeView = new com.zetacube.libzc.AdView(context);
//			adcubeView.setVisibility(View.VISIBLE);
//			adcubeView.loadAd(appid, null, false);
//			adcubeView.setOnAdViewListener(new com.zetacube.libzc.AdView.OnAdViewListener() 
//			{			
//				// 광고로딩 실패시
//				public void receiveAdError(int errorCode, String description, 
//						String failingUrl) {
//					
//					isReceive = false;
//					
//					switch (KIND) {
//					case ADAM_ADCUBE:
////						BDAdViewDestroy();
//						adamCpcAd();
//						break;
//					case TAD_ADCUBE:
////						BDAdViewDestroy();
//						tadCpcAd();
//						break;	
//					case ADCUBE:
////						BDAdViewDestroy();
//						adcubeCpcAd();
//						break;	
//					case ALL:
////						BDAdViewDestroy();
//						adamCpcAd();
//					default:
//						break;
//					}
//				}
//				
//				// 광고 로딩 완료
//				public void receiveAd(String url) {
////					min = 0;
//					
//					if ( ! isReceive )
//					{
//						adviewLinear.setVisibility(View.VISIBLE);
//						adviewLinear.addView(adcubeView, params);
//						
//						isReceive = true;
//					}
//				}
//			});
//		} catch (Exception e)
//		{
//			if (adcubeView != null)
//			{
//				BDAdViewDestroy();
//				adamCpcAd();
//			}
//		}
//	}
//	
//	private void resumeAdcubeView() {
//		if (adcubeView != null) {
//		}
//	}
//	
//	private void pauseAdcubeView() {
//		if (adcubeView != null) {
//		}
//	}
//	
//	private void destroyAdcubeView() {
//		if (adcubeView != null) {
//			if (adviewLinear.getChildCount() > 0)
//			{
//				adviewLinear.removeView(adcubeView);
//			}
//			adcubeView.setVisibility(View.GONE);
//			adcubeView.stopAd();
//		}
//	}
//	
//	// t ad //
//	
//	public void tadCpcAd() 
//	{
//		if (min >= max)
//		{
//			adamCpcAd();
//			
//			return;
//		}
//		
//		min++;
//		
//		tadView = AdView.createAdView(context);
//		tadView.setAdListener(this);
//		adviewLinear.addView(tadView);
//		adviewLinear.setVisibility(View.GONE);
////		adviewLinear.setVisibility(View.INVISIBLE);
//	}
//	
//	@Override
//	public void onFailedToReceiveAd(AdListenerResponse arg0) {
//		
////		if (min++ == max)
////		{
////			BDAdViewDestroy();
////			
////			return;
////		}
//		
//		isReceive = false;
//		
//		switch (KIND) {
//		case ADAM_TAD:
////			BDAdViewDestroy();
//			adamCpcAd();
//			break;
//		case TAD:
////			BDAdViewDestroy();
//			tadCpcAd();
//			break;	
//		case TAD_ADCUBE:
////			BDAdViewDestroy();
//			adamCpcAd();
//			break;	
//		case ALL:
////			BDAdViewDestroy();
//			adcubeCpcAd();
//		default:
//			break;
//		}
//	}
//
//	@Override
//	public void onReceiveAd() {
//		
////		min = 0;
//		
//		if ( ! isReceive )
//		{
////			destroyAdamView();
////			destroyAdcubeView();
//			
//			for (int i = 0; i < adviewLinear.getChildCount(); i++)
//			{
//				View child = adviewLinear.getChildAt(i);
//				
//				if (child instanceof MobileAdView)
//				{
//					adviewLinear.removeView(child);
//				}
//			}
//			
//			adviewLinear.setVisibility(View.VISIBLE);
//			isReceive = true;
//		}
//	}
//	
//	private void resumeTadView() {
//		if (tadView == null) {
//		}
//	}
//	
//	private void pauseTadView() {
//		if (tadView != null) {
//		}
//	}
//	
//	private void destroyTadView() {
//		if (tadView != null) 
//		{
//			if (adviewLinear.getChildCount() > 0)
//			{
//				adviewLinear.removeView(tadView);
//			}
//			tadView = null;
//		}
//	}
	
}
